%%%-------------------------------------------------------------------
%%% File    : disk_log_pool.erl
%%% Author  :  <vjache>
%%% Description : 
%%%
%%% Created :  2 Jul 2009 by  <vjache>
%%%-------------------------------------------------------------------
-module(disk_log_pool).

%% API
-export([new_factory/0,
		 alog/3,
		 alog_terms/3,
		 log_terms/3,
		 long_action/3,
		 open_log/2,
		 close_log/2,
		 close_finalize_log/2,
		 destroy_log/2]).

-include("../include/rpool.hrl").

-define(CHECKERR(Expr,ErrTag),checkerr(Expr,ErrTag)).
%%====================================================================
%% API
%%====================================================================
%%--------------------------------------------------------------------
%% Function: 
%% Description:
%%--------------------------------------------------------------------
new_factory() ->
	#rsc_factory{
			 open_fun=fun open/1,
			 close_fun=fun close/1,
			 destroy_fun=fun delete/1}.
alog(PoolName,Log,Term) ->
	svc_rpool:short_action(
	  PoolName, Log, 
	  fun(_)->
			  ?CHECKERR(disk_log:alog(Log, Term),alog_err)
	  end).
alog_terms(PoolName,Log,Terms) ->
	svc_rpool:short_action( 
	  PoolName, Log, 
	  fun(_)->
			  ?CHECKERR(disk_log:alog_terms(Log, Terms),alog_terms_err)
	  end).
log_terms(PoolName,Log,Terms) ->
	svc_rpool:short_action( 
	  PoolName, Log, 
	  fun(_)->
			  ?CHECKERR(disk_log:log_terms(Log, Terms),log_terms_err)
	  end).

long_action(PoolName,Log,DoFun) when is_function(DoFun, 1) ->
	svc_rpool:long_action(
	  PoolName, Log, 
	  DoFun).

open_log(PoolName,Log) ->
	svc_rpool:open(PoolName, Log).

close_log(PoolName,Log) ->
	svc_rpool:close(PoolName, Log).
close_finalize_log(PoolName,Log) ->
	svc_rpool:close_finalize(PoolName, Log).
destroy_log(PoolName,Log) ->
	svc_rpool:destroy(PoolName, Log).
%%====================================================================
%% Internal functions
%%====================================================================
open({rw,Filename}=Log) ->
	?CHECKERR(filelib:ensure_dir(Filename),error),
	case disk_log:open(
		   [{name,Log},
			{file,Filename}]) 
		of
		{ok,_} ->
			Log;
		{repaired, _, _, _} ->
			Log;
		{error,{file_error,_File,emfile}} ->
			throw(limit_err);
		{error,{file_error,_File,system_limit}} ->
			throw(limit_err);
		{error,Reason} ->
			throw(Reason)
	end;
open({ro,Filename}=Log) ->
	case disk_log:open(
		   [{name,Log},
			{file,Filename},
			{mode,read_only}]) of
		{ok,_} ->
			Log;
		{repaired, _, _, _} ->
			Log;
		{error,{file_error,_File,emfile}} ->
			throw(limit_err);
		{error,{file_error,_File,system_limit}} ->
			throw(limit_err);
		{error,Reason} ->
			throw(Reason)
	end.

close(Log) ->
	?CHECKERR(disk_log:close(Log),error).

delete({_,Filename}=_Log) ->
	?CHECKERR(file:delete(Filename),del_log_err).


checkerr({error,Reason},ErrTag) ->
	throw({ErrTag,Reason});
checkerr(Result,_ErrTag) ->
	Result.
